#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGridLayout>
#include <QMenu>
#include <QAction>
#include <QMenuBar>
#include <QMessageBox>
#include <QFileDialog>
#include <QColorDialog>
#include <QSettings>
#include <QTextCodec>
#include <QDomDocument>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QTimer>
#include <QThread>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("BiTOD TestKits");
    setWindowIcon(QIcon(":/Image/Icon/icon.png"));

    // 菜单栏
    QMenuBar *MenuBar = this->menuBar();
    MenuBar->setStyleSheet("background-color: #FFFAFA;");
    QMenu* filemenu = new QMenu("文件");

    QStringList slActionName;
    slActionName << "加载ini文件" << "加载xml文件" << "加载DB运行文件";
    filemenu->addAction(slActionName[0]);
    filemenu->addAction(slActionName[1]);
    filemenu->addAction(slActionName[2]);

    QMenu* settingmenu = new QMenu("设置");
    settingmenu->addAction("设置为十进制");
    settingmenu->addAction("设置为十六进制");
    settingmenu->addAction("设置为二进制");

    QMenu* helpmenu = new QMenu("Help");
    helpmenu->addAction("帮助");
    helpmenu->addAction("版本");
    helpmenu->addAction("主题");

    MenuBar->addMenu(filemenu);
    MenuBar->addMenu(settingmenu);
    MenuBar->addMenu(helpmenu);
    customUI();
    readconfig();

    connect(filemenu->actions()[0],&QAction::triggered,this,[=](bool){
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setNameFilter(tr("*.ini"));
        QStringList fileNames;
        if (QDialog::Accepted == dialog.exec())
        {
            fileNames = dialog.selectedFiles();
            inifileoperate(fileNames[0]);
        }
    });
    connect(filemenu->actions()[1],&QAction::triggered,this,[=](bool){
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setNameFilter(tr("*.xml"));
        QStringList fileNames;
        if (QDialog::Accepted == dialog.exec())
        {
            fileNames = dialog.selectedFiles();
            xmlfileoperate(fileNames[0]);
        }
    });
    // TODO：定时将从数据库读取的报文一帧一帧的发给TOD
    connect(filemenu->actions()[2],&QAction::triggered,this,[=](bool){
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setNameFilter(tr("*.db"));
        QStringList fileNames;
        if (QDialog::Accepted == dialog.exec())
        {
            fileNames = dialog.selectedFiles();
            dbfileoperate(fileNames[0]);
        }
        client->setMsgFrames(slMsgFrames);
    });

    connect(helpmenu->actions()[0],SIGNAL(triggered(bool)),this,SLOT(assitantHandler(bool)));
    connect(helpmenu->actions()[1],&QAction::triggered,this,[=](bool){
        QMessageBox msgBox;
        msgBox.setText(slConfigInfo[0]);
        msgBox.exec();
    });
    connect(helpmenu->actions()[2],&QAction::triggered,this,[=](bool){
        QColorDialog dialog(this);
        if (QDialog::Accepted == dialog.exec())
        {
            QColor color = dialog.selectedColor();
            QPalette pa = palette();
            pa.setColor(QPalette::Normal,QPalette::Window,color);
            setPalette(pa);
        }
    });
    // 将textedit内容解析到items中去
    connect(client,&TcpClient::ParseFinished,this,[=](){
        int addNum = 0;
        for(int i = 0; i < vetItems.size(); i++)
        {//大端
            QString strVal = "";
            bool ok = false;
            if( 0 != i )
            {
                addNum += vetElements[i-1].size;
            }
            for(int j = 0; j < vetElements[i].size; j++)
            {
                strVal.append(client->getParseData()[addNum + j]);
            }
            vetItems[i]->setItemText(QString::number(strVal.toULongLong(&ok,16)));
        }
    });
    connect(client,&TcpClient::AssembleMessage,this,[=](){
        QStringList slText;
        QString strDisplayText = "";
        for(int i = 0; i < vetElements.size(); i++)//vetElements有多少元素就有多少item
        {
            QString strItemText = QString::number(vetItems.at(i)->getItemText().toInt(),16);//将十进制数转换为十六进制字符串
            if(strItemText.size() < vetElements.at(i).size * 2)
            {
                QString s = "";
                for(int j = 0; j < (2 * vetElements.at(i).size - strItemText.size()); j++)
                {
                    s.append("0");
                }
                strItemText.prepend(s);
            }
            else
            {

            }
            strDisplayText.append(strItemText);
            qDebug() << strItemText << strDisplayText;
        }
        for(int i = 0; i < strDisplayText.size(); i++)
        {
            if(i % 3 == 0)
            {
                strDisplayText.insert(i," ");
            }
        }
        client->setSendAreaText(strDisplayText.toUpper());
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
/// 显示界面
void MainWindow::customUI()
{
    mainWidget= new QWidget();
    setContentsMargins(0,0,0,0);
    setCentralWidget(mainWidget);

    QVBoxLayout *mainlayout = new QVBoxLayout;
    QGridLayout* layout = new QGridLayout;
    layout->setSpacing(1);
    mainlayout->addLayout(layout);
    mainWidget->setLayout(mainlayout);

    loadWidget = new QWidget;// 加载的窗口在这里实现
    layout->addWidget(loadWidget,0,0,1,1);

    client = new TcpClient;
    QGridLayout *bottomlayout = new QGridLayout;
    bottomlayout->addWidget(client);
    mainlayout->addLayout(bottomlayout);
}

void  MainWindow::itemchangedHandler(int num,quint64 value)
{
    //qDebug() << num << value;
}

void  MainWindow::assitantHandler(bool b)
{
    QMessageBox msgBox;
    msgBox.setText(slConfigInfo[1] + slConfigInfo[2] + slConfigInfo[3] + slConfigInfo[4] );
    msgBox.exec();
}
/*
* @brief ini 配置文件读取
* @note 通过文件名读取指定配置文件
*/
void MainWindow::inifileoperate(const QString& filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    QTextStream in(&file);
    int indexNum = 0;
    while (!in.atEnd()) {
        QString line = in.readLine();
        if(line.contains("index"))
        {
            indexNum++;
        }
    }
    vetElements.clear();
    QSettings settings(filename,QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("utf-8"));
    for(int i = 0; i < indexNum; i++)
    {
        Element_ST stElement;
        stElement.size = settings.value(QString("Index%1/size").arg(i)).toInt();
        stElement.strName = settings.value(QString("Index%1/Name").arg(i)).toString();
        vetElements.append(stElement);
    }
    updateUi();
}
/*
* @brief xml 配置文件读取
* @note 通过文件名读取指定配置文件
*/
void MainWindow::xmlfileoperate(const QString& filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }

    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();

    vetElements.clear();
    QDomElement root= doc.documentElement();
    QDomNode node=root.firstChild();
    while(!node.isNull())
    {
        if(node.isElement())
        {
            QDomElement e=node.toElement();
            QDomNodeList list=e.childNodes();
            for(int i = 0;i < list.count();i++)
            {
                QDomNode Domnode = list.at(i);
                if(node.isElement())
                {
                    Element_ST stElement;
                    stElement.size = Domnode.childNodes().at(2).toElement().text().toInt();
                    stElement.strName = Domnode.childNodes().at(1).toElement().text();
                    vetElements.append(stElement);
                }
            }
        }
        node = node.nextSibling();
     }
    updateUi();
}
/*
* @brief 读取配置文件后重新加载界面
* @note
*/
void MainWindow::updateUi()
{
    int i = 0;
    QGridLayout* layout = new QGridLayout;
    vetItems.clear();
    for(int row = 0; row < ( vetElements.size() / 8) + 1; row++)
    {
        for(int col = 0;col < 8; col++)
        {
            if(vetElements.size() > i)
            {
                QString strName = vetElements.at(i).strName;
                Item = new ItemWidget(i++,strName,0);
                vetItems.append(Item);
                connect(Item,SIGNAL(cellchanged(int,quint64)),this,SLOT(itemchangedHandler(int,quint64)));
                layout->addWidget(Item,row,col);
            }
        }
    }
    loadWidget->setLayout(layout);
    update();
}

void MainWindow::readconfig()
{
    QSettings settings(QCoreApplication::applicationDirPath() + "/config.ini",QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("utf-8"));
    slConfigInfo << settings.value("Index/Version").toString() \
                 << settings.value("Index/helpinfo1").toString() \
                 << settings.value("Index/helpinfo2").toString() \
                 << settings.value("Index/helpinfo3").toString() \
                 << settings.value("Index/helpinfo4").toString();
}

void MainWindow::dbfileoperate(const QString& filename)
{
    QVector<int> vetIndexOfQuery;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(filename);
    if(db.open())
    {
        QSqlQuery query(db);
        query.setForwardOnly(true);//select count(id) from message where binarystring like "% 00 00 27 12%37%" and text like "%c5%"
        if(query.exec("select count(id) from message where binarystring like \"% 00 00 27 12%37%\" and text like \"%c5%\";"))
        {
            if(query.next())
            {
                if(query.value(0).toInt() > 0)
                {// L
                    query.exec("select id from message where text like \"%c5%\" and binarystring like \"% 00 00 27 12%37%\" order by NonSaftyTime asc;");
                    vetIndexOfQuery.clear();
                    while(query.next())
                    {
                        vetIndexOfQuery.append(query.value(0).toInt());
                    }
                    for(int i = 0; i < vetIndexOfQuery.size();i++)
                    {
                        QString strQuery = QString("select binarystring from message where text like \"%c5%\" and binarystring like \"% 00 00 27 12%37%\"  and id = %1 order by NonSaftyTime asc;").arg(vetIndexOfQuery.at(i));
                        if(query.exec(strQuery))
                        {
                            while(query.next())
                            {
                                if(query.value(0).toString().split(" 00 00 a0 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 a0 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else if(query.value(0).toString().split(" 00 00 a8 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 a8 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else if(query.value(0).toString().split(" 00 00 b0 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 b0 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else if(query.value(0).toString().split(" 00 00 98 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 98 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                            }
                        }
                    }
                }
                else
                {//R
                    query.exec("select id from message where text like \"%c5%\" and binarystring like \"%00 00 27 10%37%\" order by NonSaftyTime asc;");
                    vetIndexOfQuery.clear();
                    while(query.next())
                    {
                        vetIndexOfQuery.append(query.value(0).toInt());
                    }
                    for(int i = 0; i < vetIndexOfQuery.size();i++)
                    {
                        QString strQuery = "select binarystring from message where text like \"%c5%\" and binarystring like \"% 00 00 27 10 %37%\"  and id = " + QString::number(vetIndexOfQuery.at(i)) + " order by NonSaftyTime asc;";
                        //QString strQuery = QString("select binarystring from message where text like \"%c5%\" and binarystring like \"% 00 00 27 10 %37%\"  and id = %1 order by NonSaftyTime asc;").arg(vetIndexOfQuery.at(i));
                        if(query.exec(strQuery))
                        {
                            while(query.next())
                            {
/*                                if(query.value(0).toString().split(" 00 00 a0 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 a0 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else if(query.value(0).toString().split(" 00 00 98 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 98 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else if(query.value(0).toString().split(" 00 00 a8 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 a8 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                                else */if(query.value(0).toString().split(" 00 00 91 ").size() == 2)
                                {
                                    slMsgFrames << query.value(0).toString().split(" 00 00 91 ")[1];
                                    //qDebug() << slMsgFrames;
                                }
                            }
                        }
                        else
                        {
                            qDebug() << query.lastError();
                        }
                    }
                }
            }
        }
    }
}

